package com.zzyl.service.impl;

import com.zzyl.entity.AccraditationRecord;
import com.zzyl.mapper.AccraditationRecordMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AccraditationRecordService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RecordVo;
import com.zzyl.vo.UserRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class AccraditationRecordServiceImpl implements AccraditationRecordService {


    @Autowired
    private AccraditationRecordMapper accraditationRecordMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String RECORD_STEP_NO_PRE="RECORD:";

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 保存审核记录
     *
     * @param recordVo
     */
    @Override
    public void insert(RecordVo recordVo) {

        AccraditationRecord accraditationRecord = new AccraditationRecord();
        accraditationRecord.setApproverId(recordVo.getUserId());
        accraditationRecord.setBussniessId(recordVo.getId());
        accraditationRecord.setCreateTime(LocalDateTime.now());
        accraditationRecord.setType(recordVo.getType());
        accraditationRecord.setOpinion(recordVo.getOption());
        accraditationRecord.setApproverName(recordVo.getRealName());
        accraditationRecord.setCurrentStep(recordVo.getStep());
        accraditationRecord.setAuditStatus(recordVo.getStatus());
        accraditationRecord.setHandleType(recordVo.getHandleType());
        //审核的步骤，是自增的
        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE+recordVo.getId()).increment());
        //寻找下一个审核人
        if(ObjectUtil.isNotEmpty(recordVo.getNextAssignee())){
            //查询审核人的角色和姓名
            List<UserRoleVo> userRoleVos = userRoleMapper.selectByUserId(recordVo.getNextAssignee());
            UserRoleVo userRoleVo = userRoleVos.get(0);

            accraditationRecord.setNextApproverRole(userRoleVo.getRoleName());
            accraditationRecord.setNextApprover(userRoleVo.getUserName());
            accraditationRecord.setNextApproverId(userRoleVo.getId());
            accraditationRecord.setNextStep(recordVo.getNextStep());
        }


        accraditationRecordMapper.insert(accraditationRecord);
    }
}